/**
 * @file: todo: 登录页表单
 * @author: Lengxx
 * @date: 2023-07-11
 */
import _ from 'lodash-es'
import { login } from '@/apis/users'
import { encryptCode } from '@/utils/crypt'
import { useNavigate } from 'react-router-dom'
import { loginAuthStorage } from '@/utils/storage'
import { Button, message, Input, Form } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { useDebounceFn, useLocalStorageState, useRequest } from 'ahooks'

type FieldType = {
  username: string,
  password: string
}

const LoginForm = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();
  const [, setUserInfo] = useLocalStorageState('Userinfo');
  const [__, setToken] = useLocalStorageState('Authorization')
  const { run: onDebounceLogin } = useDebounceFn(handleLogin, { wait: 500 });
  const loginRequest = useRequest(login, { manual: true });


  /** 表单提交事件 */
  async function handleLogin(data: FieldType) {
    if (data) {
      const resp = await loginRequest.runAsync({ ...data, password: encryptCode(data.password) });
      if (resp.status === 200) {
        messageApi.success('登录成功');
        const token = 'Bearer ' + _.get(resp, 'data.tokeninfo.tokenValue');
        const userData = _.get(resp, 'data.userinfo');

        // 缓存登录信息
        setUserInfo(userData);
        setToken(token);
        loginAuthStorage.setToken(token);

        setTimeout(() => {
          navigate('/')
        }, 500)
      }
    }
  }

  return (
    <>
      {contextHolder}

      <Form
        form={form}
        autoComplete='off'
        className='login-form'
        onFinish={onDebounceLogin}
      >
        <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
          <Input
            allowClear
            placeholder="用户名"
            prefix={<UserOutlined />}
          />
        </Form.Item>
        <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
          <Input
            allowClear
            placeholder="密码"
            type="password"
            prefix={<LockOutlined />} />
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            loading={loginRequest.loading}
            className='login-btn'>登 录</Button>
        </Form.Item>
      </Form>
    </>
  )
}

export default LoginForm